import TauPage from '@/components/TauPage';
import TauActionPanel from '@/components/TauActionPanel';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { column } from './stores/definitions';
import { toJS } from 'mobx';
import DrawerFooter from '@/components/DrawerFooter';
import SuperAddition from './components/SuperAddition';

const tableId = uniqueId('tauTable-');

function Orders({ onCancel, modal: orderMode }) {
  const { appliedDetailStore: store } = useStore();
  const [superAddition, setSuperAddition] = useState();

  useEffect(() => { if (orderMode[1]?.startsWith?.('toClose')) handleCancel(); }, [orderMode]);

  useEffect(() => {
    (async () => {
      await store.getCouponBatches({});
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { upDate, couponBatchIds, ...searchArgs } = params.values;
    const [from, to] = upDate || [];
    store.search = {
      from,
      to,
      couponBatchIds: couponBatchIds ? [couponBatchIds] : null,
      ...searchArgs,
    };
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    onCancel?.();
  };

  const onClose = () => {
    setSuperAddition({ visible: false });
  };

  const handleBatchSubmit = async (result) => {
    try {
      const { count: quantity } = result;
      const { activityId: id, couponBatchId: batchId, customerUsername: username } = superAddition?.record || {};
      Dialog.confirm({
        content: t`确定要追加【${id}】吗?`,
        onOk: async () => await ensureEdit(id, { activityId: id, batchId, username, quantity }),
      });
    } catch (error) {
      Message.error({ content: t`追加错误` });
    }
  };

  const ensureEdit = async (id, args) => {
    try {
      await store.api.superAddition(id, args);
      Message.success({ content: t`追加成功` });
      setSuperAddition({});
      await store.query();
    } catch (error) {
      Message.error({ content: t`追加失败`, duration: 7000 });
      throw error;
    }
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'couponBatchIds',
            type: 'select',
            props: {
              placeholder: t`请选择卡券批次`,
              style: { width: 200 },
              dataSource: store.couponIds,
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('customerPhone', { width: 128 }),
            column('customerFullName', { width: 128 }),
            column('couponBatchName', { width: 138 }),
            column('conversionQuantity', { width: 99 }),
            column('requestedQuantity', { width: 99 }),
            {
              title: t`操作`,
              dataIndex: 'activityNumber',
              width: 138,
              cell: (_, i, record) => (
                <Button type="primary" text onClick={() => setSuperAddition({ visible: 'open', onClose, record })}>{t`追加`}</Button>
              ),
            },
          ]}
        />
      </div>
      <DrawerFooter>
        <Button style={{ marginLeft: 8 }} onClick={() => handleCancel()}>{t`取消`}</Button>
      </DrawerFooter>
      <SuperAddition modal={superAddition} onSubmit={handleBatchSubmit} />
    </TauPage>
  );
}

export default observer(Orders);
